/**
 * 通知模块状态管理
 * 使用pinia管理通知状态
 * @author LYC
 * @date 2025-09-20
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { NotificationConfig, NotificationItem, NotificationOptions } from './type'

/**
 * 通知模块状态管理
 */
export const useNotificationStore = defineStore('notification', () => {
  // 状态
  const notifications = ref<NotificationItem[]>([])
  const unsubscribeClickListener = ref<(() => void) | null>(null)

  // 计算属性
  const unreadCount = computed(() => notifications.value.filter((n) => !n.read).length)
  const latestNotification = computed(() =>
    notifications.value.length > 0 ? notifications.value[0] : null
  )

  // 初始化通知监听器
  const initListeners = (): void => {
    console.log('222')

    // 如果已经有监听器了先清理
    if (unsubscribeClickListener.value) {
      unsubscribeClickListener.value()
    }

    // 设置点击通知的监听器
    unsubscribeClickListener.value = window.electron.notification.onClicked((data) => {
      if (data.id) {
        markAsRead(data.id)
      }
    })
  }

  // 检测当前平台
  const getPlatform = async (): Promise<'win32' | 'darwin' | 'linux' | 'unknown'> => {
    try {
      const platform = await window.electron.ipcRenderer.invoke('get-platform')
      if (platform === 'win32' || platform === 'darwin' || platform === 'linux') {
        return platform as 'win32' | 'darwin' | 'linux'
      }
    } catch (error) {
      console.error('获取平台信息失败:', error)
    }
    return 'unknown'
  }

  // 检查特性是否被当前平台支持
  const isFeatureSupported = async (feature: string): Promise<boolean> => {
    const platform = await getPlatform()

    switch (feature) {
      case 'actions':
        // 操作按钮支持
        return platform === 'darwin' || platform === 'win32'

      case 'reply':
        // 直接回复功能支持
        return platform === 'darwin'

      case 'sound':
        // 声音支持
        return platform === 'darwin' || platform === 'win32'

      case 'silent':
        // 静默通知支持
        return true // 所有平台都支持

      case 'urgency':
        // 紧急程度支持
        return platform === 'linux'

      default:
        return false
    }
  }

  // 优化通知配置以适应当前平台
  const optimizeForPlatform = async (config: NotificationConfig): Promise<NotificationConfig> => {
    const platform = await getPlatform()
    const optimized = { ...config }

    // 根据平台移除不支持的功能
    if (platform === 'win32') {
      // Windows特定优化
      if (optimized.actions && optimized.actions.length > 3) {
        // Windows最多支持3个操作按钮
        optimized.actions = optimized.actions.slice(0, 3)
      }
      delete optimized.subtitle // Windows不支持
    } else if (platform === 'darwin') {
      // macOS特定优化
      if (optimized.body && optimized.body.length > 256) {
        optimized.body = optimized.body.substring(0, 253) + '...'
      }
    } else if (platform === 'linux') {
      // Linux特定优化
      delete optimized.subtitle
      delete optimized.hasReply
      delete optimized.replyPlaceholder
      delete optimized.closeButtonText
      delete optimized.actions
    }

    return optimized
  }

  // 显示通知
  const showNotification = async (
    config: NotificationConfig,
    options?: NotificationOptions
  ): Promise<string> => {
    try {
      // 优化通知配置以适应当前平台
      const optimizedConfig = await optimizeForPlatform(config)

      // 获取是否使用系统通知的设置
      const useSystemNotification =
        options?.useSystemNotification !== undefined ? options.useSystemNotification : true // 默认使用系统通知

      let id = ''

      // 如果启用系统通知，则尝试显示
      if (useSystemNotification) {
        // 发送系统通知
        id = await window.electron.notification.show(optimizedConfig)

        // 如果没有返回ID，说明通知显示失败
        if (!id) {
          console.warn('系统通知显示失败，可能是权限不足或处于免打扰模式')
        }
      }

      // 如果没有获得ID（不使用系统通知或系统通知失败），则生成一个本地ID
      if (!id) {
        id = `local_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
      }

      // 默认保存到历史记录
      const saveToHistory = options?.saveToHistory !== false

      // 保存到历史记录
      if (saveToHistory) {
        const notificationItem: NotificationItem = {
          id,
          config, // 保存原始配置，而不是优化后的
          createdAt: Date.now(),
          read: false
        }
        // 将新通知添加到数组前面
        notifications.value = [notificationItem, ...notifications.value]
      }
      return id
    } catch (error) {
      console.error('显示通知失败:', error)
      return '' // 返回空字符串表示失败
    }
  }

  // 关闭通知
  const closeNotification = async (id: string): Promise<boolean> => {
    try {
      const result = await window.electron.notification.close(id)
      return result
    } catch (error) {
      console.error('Failed to close notification:', error)
      throw error
    }
  }

  // 标记通知为已读
  const markAsRead = (id: string): void => {
    const index = notifications.value.findIndex((n) => n.id === id)
    if (index !== -1) {
      notifications.value[index].read = true
    }
  }

  // 标记所有通知为已读
  const markAllAsRead = (): void => {
    notifications.value = notifications.value.map((n) => ({ ...n, read: true }))
  }

  // 清除通知历史
  const clearHistory = (): void => {
    notifications.value = []
  }

  // 清除旧通知（保留指定数量）
  const clearOldNotifications = (keepCount = 50): void => {
    if (notifications.value.length > keepCount) {
      notifications.value = notifications.value.slice(0, keepCount)
    }
  }

  // 返回暴露的属性和方法
  return {
    // 状态
    notifications,

    // 计算属性
    unreadCount,
    latestNotification,

    // 方法
    initListeners,
    showNotification,
    closeNotification,
    markAsRead,
    markAllAsRead,
    clearHistory,
    clearOldNotifications,

    // 平台相关
    getPlatform,
    isFeatureSupported,
    optimizeForPlatform
  }
})
